#include "../source/server.hpp"

#include <iostream>
#include <time.h>
// #include <stdlib.h> // atoi 函数需要的头文件

using namespace std;

std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;

void ConnectionDestroy(const PtrConnection &conn)
{
    _conns.erase(conn->Id());
}

void OnConnected(const PtrConnection &conn)
{
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}

void OnMessage(const PtrConnection &conn, Buffer *buf)
{
    DBG_LOG("%s", buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "Hello World";
    conn->Send(str.c_str(), str.size());

    conn->Shutdown(); // 测试 server 接收一次数据就中断 client
}

void Acceptor(EventLoop *loop, Channel *server_channel)
{
    int server_fd = server_channel->Fd();
    int newfd = accept(server_fd, NULL, NULL);
    if (newfd < 0)
        return;

    conn_id++;
    PtrConnection conn(new Connection(loop, conn_id, newfd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2)); // 为新的通信套接字设置可读事件的回调函数
    conn->SetSrvClosedCallback(std::bind(ConnectionDestroy, std::placeholders::_1));
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));

    conn->EnableInactiveRelease(10); // 启动非活跃超时销毁
    conn->Established();             // 就绪初始化

    _conns.insert(std::make_pair(conn_id, conn));
}

int main(void)
{
    srand(time(nullptr));
    // Poller poller; // 管理多个 Channel 的类
    EventLoop loop;
    Socket server;
    server.CreateServer(8500);
    // 为监听套接字，创建一个Channel进行事件的管理，以及事件的处理
    Channel channel(&loop, server.Fd());
    channel.SetReadCallback(std::bind(Acceptor, &loop, &channel)); // 回调中，获取新连接，并未新连接创建Channel，并添加监控
    channel.EnableRead();
    while (true)
    {
        loop.start();

        sleep(1);
    }
    server.Close();

    return 0;
}
